#include "threadPool.h"

// 初始化哈希表
hash_table_t* hash_init(int size) {
    hash_table_t *ht = malloc(sizeof(hash_table_t));
    ht->size = size;
    ht->buckets = calloc(size, sizeof(hash_node_t*));
    return ht;
}

// 哈希函数
int hash_func(int fd, int size) {
    return fd % size;
}

// 插入/更新哈希表
void hash_upsert(hash_table_t *ht, int fd, int slot_index) {
    int idx = hash_func(fd, ht->size);
    hash_node_t *node = ht->buckets[idx];
    
    // 查找是否已存在
    while (node) {
        if (node->fd == fd) {
            node->slot_index = slot_index;
            return;
        }
        node = node->next;
    }
    
    // 不存在则创建新节点
    hash_node_t *new_node = malloc(sizeof(hash_node_t));
    new_node->fd = fd;
    new_node->slot_index = slot_index;
    new_node->next = ht->buckets[idx];
    ht->buckets[idx] = new_node;
}

// 从哈希表中获取槽位索引
int hash_get(hash_table_t *ht, int fd) {
    int idx = hash_func(fd, ht->size);
    hash_node_t *node = ht->buckets[idx];
    
    while (node) {
        if (node->fd == fd) {
            return node->slot_index;
        }
        node = node->next;
    }
    return -1; // 未找到
}

// 从哈希表中删除
void hash_remove(hash_table_t *ht, int fd) {
    int idx = hash_func(fd, ht->size);
    hash_node_t **prev = &ht->buckets[idx];
    hash_node_t *current = ht->buckets[idx];
    
    while (current) {
        if (current->fd == fd) {
            *prev = current->next;
            free(current);
            return;
        }
        prev = &current->next;
        current = current->next;
    }
}
// 初始化集合
void fdset_init(FdSet *set, int capacity) {
    set->fds = malloc(capacity * sizeof(int));
    set->count = 0;
    set->capacity = capacity;
}

// 添加元素到集合
void fdset_add(FdSet *set, int fd) {
    if (set->count < set->capacity) {
        set->fds[set->count++] = fd;
        printf("set->count = %d\n",set->count);
    }
}

// 从集合中移除元素
void fdset_remove(FdSet *set, int fd) {
    for (int i = 0; i < set->count; i++) {
        if (set->fds[i] == fd) {
            // 用最后一个元素替换
            set->fds[i] = set->fds[set->count - 1];
            set->count--;
            return;
        }
    }
}